//
//  ReceiveSenCashBoxVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/15.
//
// 【首页-电子台账】接、送库款箱记录

import Foundation
import UIKit

class ReceiveSenCashBoxVC: BaseFormVC {
    let listV = ReceiveSenCashBoxView()

    var model: StandingBookHistoryModal?

    // MARK: - Override
    override func reloadData() {
        listV.deptName = deptName ?? ""
        listV.registerField(withValidator: validator)
        queryHistory()
    }
    
    func queryHistory() {
        let param = StandingBookNotLoginParam(bootType: modal.typeValue, deptId: "\(deptId ?? -1)")
        API.getStandingBookQueryHistory(withJson: param) { responseModel in
            self.model = responseModel.model
            if self.model?.isHistory == true {
                DispatchQueue.main.async {
                    self.historAlert()
                }
            } else {
                self.listV.val10TF.value = self.checkModal?.fqrxm
                self.listV.val11TF.value = self.checkModal?.jsrxm
            }
        }
    }
   
    func historAlert() {
        let alertC = UIAlertController(title: "任务未完成，是否继续填写", message: nil, preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "否", style: .cancel, handler: { action in
            self.listV.val10TF.value = self.checkModal?.fqrxm
            self.listV.val11TF.value = self.checkModal?.jsrxm
        })
        let okAction = UIAlertAction(title: "是", style: .default, handler: { action in
            if let history = self.model?.history {
                DispatchQueue.main.async {
                    self.listV.updateHistory(withM: history)
                    self.listV.val12TF.value = self.checkModal?.fqrxm
                    self.listV.val13TF.value = self.checkModal?.jsrxm
                }
            }
        })
        alertC.addAction(cancelAction)
        alertC.addAction(okAction)
        self.present(alertC, animated: true)
    }
    
    override func didValidated(withMode mode: String?) {
        view.showToastActivity()
        if let mode = mode {
            upload(withMode: mode)
        } else {
            upload(withMode: "2")
        }
    }
    
    func upload(withImg vimg: UIImage?, completion: ((_ imgUrl: String?) -> Void)? = nil) {
        if let img = vimg {
            if let v1Path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img) {
                API.postStandingBookUpload(withImage: v1Path) { responseModel in
                    completion?(responseModel.model?.imgUrl)
                }
            } else {
                completion?(nil)
            }
        } else {
            completion?(nil)
        }
    }
    
    func upload(withMode mode: String) {
        var valPam = ElecParam(bookType: modal.typeValue, mode: mode)
        if let hsId = checkModal?.hsId {
            valPam.hsId = "\(hsId)"
        }
        valPam.tjrq = Date.dateToUp(listV.tjrqTF.value ?? "")
        valPam.attrValue0 = Date.dateToUp(listV.val0TF.value ?? "")
        valPam.attrValue1 = listV.val1TF.value
        valPam.attrValue2 = listV.val2TF.value
        valPam.attrValue5 = Date.dateToUp(listV.val5TF.value ?? "")
        valPam.attrValue6 = listV.val6TF.value
        valPam.attrValue7 = listV.val7TF.value
        
        valPam.attrValue10 = listV.val10TF.value
        valPam.attrValue11 = listV.val11TF.value
        valPam.attrValue12 = listV.val12TF.value
        valPam.attrValue13 = listV.val13TF.value
        
        self.didUpload(withData: valPam)

//        upload(withImg: listV.val3TF.img) { imgUrl1 in
//            valPam.attrValue3 = imgUrl1
//            self.upload(withImg: self.listV.val4TF.img) { imgUrl2 in
//                valPam.attrValue4 = imgUrl2
//                self.upload(withImg: self.listV.val8TF.img) { imgUrl3 in
//                    valPam.attrValue8 = imgUrl3
//                    self.upload(withImg: self.listV.val9TF.img) { imgUrl4 in
//                        valPam.attrValue9 = imgUrl4
//                        self.didUpload(withData: valPam)
//                    }
//                }
//            }
//        }
    }
    
    func didUpload(withData valPam: ElecParam) {
        // 完成校验
        do {
            var jsonParam = CommonJsonParam()
            let data: Data = try JSONEncoder().encode(valPam)
            let string = String(data: data, encoding: String.Encoding.utf8)
            jsonParam.jsonStr = string
            API.postStandingBookSave(withJson: jsonParam) { responseModel in
                self.view.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.view.showToast(witMsg: responseModel.errorMessage)
                    self.navigationController?.popViewController(animated: false)
                    self.confirmSuccessWith?()
                }
            }
        } catch {
            self.view.hideToastActivity()
            print("ReceiveSenCashBoxVC didValidated error", error)
        }
    }
    
    override func setupUI() {
        listV.confirmNoPersonWith = { () -> () in
            self.handelNoPerson()
        }
        listV.val5TF.didSelectDateWith = { (date) -> () in
            self.listV.val10TF.value = self.checkModal?.fqrxm
            self.listV.val11TF.value = self.checkModal?.jsrxm
        }
        listV.val0TF.didSelectDateWith = { (date) -> () in
            self.listV.val12TF.value = self.checkModal?.fqrxm
            self.listV.val13TF.value = self.checkModal?.jsrxm
        }
        listV.saveBtn.addTarget(self, action: #selector(saveTapped), for: .touchUpInside)
        listV.submitBtn.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
        view.addSubview(listV)
        listV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}
